package com.eightbears.beboy.ui.login;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.entity.SuccessEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.WeiChatEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.et_nickname)
    EditText et_nickname;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.btn_submit)
    Button btn_submit;
    @BindView(R.id.progress_wheel)
    ProgressWheel progress_wheel;
    @BindView(R.id.ll_phone_num)
    LinearLayout ll_phone_num;
    @BindView(R.id.et_phone_num)
    EditText et_phone_num;
    @BindView(R.id.btn_get_code)
    TextView btn_get_code;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.et_invite)
    EditText et_invite;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;

    private int millisInFuture = 30000;
    private int countDownInterval = 1000;
    private String nickName;
    private String openId = "";
    private String wChatToken = "";
    private String securityCode;
    private String phoneNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_register);
    }

    @Override
    protected void initData() {
        WeiChatEntity WChatEntity = SPUtil.getWChat();
        ll_phone_num.setVisibility(View.GONE);
        phoneNum = getIntent().getStringExtra(LoginActivity.PARAMS_REGISTER_PHONE);
        securityCode = getIntent().getStringExtra(LoginActivity.PARAMS_REGISTER_CODE);

        if (securityCode == null) {
            if (null != WChatEntity) {
                openId = WChatEntity.getOpenid();
                wChatToken = WChatEntity.getAccess_token();
                ll_phone_num.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void initEvent() {
        et_phone_num.addTextChangedListener(watcher);
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_submit)
    void register() {

        if (!isNetWorkConnected(this))
            return;

        if (!validInput())
            return;

        progress_wheel.setVisibility(View.VISIBLE);
        if (ll_phone_num.getVisibility() == View.VISIBLE) {
            if (validPhoneNum() && validSecurityCode()) {

                replaceLoginUnable();
                submitData();
            }
        } else {
            submitData();
        }

    }

    @OnClick(R.id.btn_get_code)
    void getCode() {
        if (!validPhoneNum()) {
            return;
        }
        progress_wheel.setVisibility(View.VISIBLE);
        replaceButtonUnable();
        eventButtonUnable();
        timer.start();
        getNetCodeData();
    }


    /**
     * 获取网络信息请求验证码接口
     */
    private void getNetCodeData() {
        //请求网络
        OkHttpUtils.post().url(CommonAPI.URL_VERIFICATION_CODE)
                .addParams("mobile", phoneNum)//请求带上11位手机号码
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                progress_wheel.setVisibility(View.GONE);
                ShowToast.showShortToast(R.string.alert_code_send_success);
            }

            @Override
            public void onError(Call call, Exception e) {
                progress_wheel.setVisibility(View.GONE);
                timer.cancel();
                replaceButtonClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(RegisterActivity.this, status_error);
            }

        });
    }

    private void submitData() {
        OkHttpUtils.post().url(CommonAPI.URL_REGISTER)
                .addParams("open_id", openId)
                .addParams("access_token", wChatToken)//编辑后名称
                .addParams("nickname", nickName)
                .addParams("mobile", phoneNum)
                .addParams("code", securityCode)
                .addParams("unique_id", CommonUtils.getAndroidId(getApplication()))
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    MobclickAgent.onProfileSignIn(String.valueOf(userEntity.getData().getUser_id()));
                    SPUtil.saveUserInfo2Local(userEntity);
                    submitInvite();
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                replaceLoginClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

//    上传请求请求码
    private void submitInvite() {
        OkHttpUtils.post().url(CommonAPI.URL_INVITE_FRIEND)
                .addParams("code", et_invite.getText().toString().trim())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                progress_wheel.setVisibility(View.GONE);
                SuccessEntity successEntity = GsonUtil.fromJson(response, SuccessEntity.class);
                if (successEntity.getStatus_code() == Integer.valueOf(CONNECTION_STATUS_SUCCESS)) {
                    startLocalActivityAndClear(RegisterActivity.this, MainActivity.class);
                    finish();
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                progress_wheel.setVisibility(View.GONE);
                replaceLoginClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    private boolean validSecurityCode() {
        securityCode = et_code.getText().toString().trim();
        if (securityCode.length() != 4) {
            ShowToast.showShortToast(R.string.error_security_code);
            return false;
        }
        return true;
    }

    private boolean validPhoneNum() {
        phoneNum = et_phone_num.getText().toString().trim();
        if (!CommonUtils.isPhoneNum(phoneNum)) {
            ShowToast.showShortToast(R.string.error_phone_num_input);
            return false;
        }
        return true;
    }

    private boolean validInput() {
        nickName = et_nickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickName)) {
            ShowToast.showShortToast(getString(R.string.alert_nickname_empty));
            return false;
        }

        return true;
    }

    private void replaceButtonClickable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setText(getText(R.string.text_get_security_code));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_get_code.setFocusable(true);
        btn_get_code.setClickable(true);
    }

    private void replaceButtonUnable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
    }

    private void eventButtonUnable() {
        btn_get_code.setFocusable(false);
        btn_get_code.setClickable(false);
    }

    private void replaceLoginClickable() {
        btn_submit.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_submit.setText(getText(R.string.ok));
        btn_submit.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_submit.setFocusable(true);
        btn_submit.setClickable(true);
    }

    private void replaceLoginUnable() {
        btn_submit.setTextColor(getResources().getColor(R.color.text_other_info_color));
        btn_submit.setText(R.string.alert_login);
        btn_submit.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
        btn_submit.setFocusable(false);
        btn_submit.setClickable(false);
    }

    private final TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) { }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 11) {
                replaceButtonClickable();
            } else {
                replaceButtonUnable();
            }
        }
    };


    CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {

            btn_get_code.setText(millisUntilFinished / countDownInterval + getString(R.string.alert_code_count_down));
        }

        @Override
        public void onFinish() {
            replaceButtonClickable();
        }
    };

}
